package com.mine.androidlearn.api.sign;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

/**
 * MD5工具类
 *
 * @author mine
 * @version V1.0 2018/8/6 22:33
 */
public final class Md5Util {

    /**
     * Hex 常量表
     */
    private static final char hexDigits[] = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'
    };
    /**
     * 计算字符串的MD5值
     *
     * @param text 要计算MD5的字符串
     * @return MD5字符串
     */
    public static final String getStringMD5(final String text) {

        String md5String = "";
        try {
            byte arrByte[] = text.getBytes("UTF-8");
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(arrByte);
            byte arrMD5Byte[] = messageDigest.digest();
            char arrChar[] = new char[arrMD5Byte.length * 2];
            int i = 0;
            for (byte b : arrMD5Byte) {
                arrChar[i++] = hexDigits[b >>> 4 & 0xf];
                arrChar[i++] = hexDigits[b & 0xf];
            }
            md5String = new String(arrChar);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return md5String;
    }

    /**
     * 计算字符串的MD5值
     *
     * @param text 要计算MD5的字符串
     * @return MD5字符串
     */
    public static final String getStringMD5(final String text, String charset) {

        String md5String = "";
        try {
            byte arrByte[] = text.getBytes(charset);
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(arrByte);
            byte arrMD5Byte[] = messageDigest.digest();
            char arrChar[] = new char[arrMD5Byte.length * 2];
            int i = 0;
            for (byte b : arrMD5Byte) {
                arrChar[i++] = hexDigits[b >>> 4 & 0xf];
                arrChar[i++] = hexDigits[b & 0xf];
            }
            md5String = new String(arrChar);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return md5String;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

    }
}
